package com.dtjd.playcoinmonkey.activities;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.dtjd.playcoinmonkey.R;
import com.dtjd.playcoinmonkey.bean.HttpParaBean;
import com.dtjd.playcoinmonkey.databinding.ActivityAddRecommendBinding;
import com.dtjd.playcoinmonkey.utils.Network;
import com.dtjd.playcoinmonkey.utils.Tools;
import com.github.dhaval2404.imagepicker.ImagePicker;
import com.google.gson.JsonParser;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AddRecommendActivity extends AppCompatActivity {
    private ActivityAddRecommendBinding binding;
    private int originWidth=0;
    private File post_file;
    private ActivityResultLauncher<Intent> launcher;
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.add_recommend_post, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (android.R.id.home==item.getItemId()){ finish(); }
        if (item.getItemId()==R.id.menu_add_recommend_post){ post(); }
        return super.onOptionsItemSelected(item);
    }
    private void post() {
        if (binding.addRecommendTitle.getText().toString().equals("")){
            Tools.toast(getResources().getString(R.string.title_cant_blank));
            return;
        }
        if (binding.addRecommendEdit.getText().toString().equals("")){
            Tools.toast(getResources().getString(R.string.content_cant_blank));
            return;
        }
        boolean has;
        if (post_file!=null){
            has= post_file.exists();
        }else {
            has=false;
        }
        List<HttpParaBean> list=new ArrayList<>();
        list.add(new HttpParaBean("token","token"));
        list.add(new HttpParaBean("title",binding.addRecommendTitle.getText().toString()));
        list.add(new HttpParaBean("content",binding.addRecommendEdit.getText().toString()));
        if (has){
            Network.upload("admin/addRecommend", post_file,list, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    runOnUiThread(() -> {
                        try {
                            Tools.toast(JsonParser.parseString(Objects.requireNonNull(response.body()).string()).getAsJsonObject().get("datalist").toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (post_file!=null){
                            if (post_file.exists())post_file.delete();
                        }
                        finish();
                    });
                }
            });
        }else {
            Network.post(list,"admin/addRecommend", new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    runOnUiThread(() -> {
                        try {
                            Tools.toast(new JSONObject(Objects.requireNonNull(response.body()).string()).getString("datalist"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (post_file!=null){
                            if (post_file.exists())post_file.delete();
                        }
                        finish();
                    });
                }
            });
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.R)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding= ActivityAddRecommendBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setTitle(getResources().getString(R.string.add_recommend));
        ActionBar actionbar = getSupportActionBar();
        if (actionbar!=null){
            actionbar.setDisplayHomeAsUpEnabled(true);
            actionbar.setHomeButtonEnabled(true);
        }
        originWidth= Tools.dip2px(this,binding.addRecommendImg.getLayoutParams().width);
        binding.addRecommendImg.setOnClickListener(view -> {
            ViewGroup.LayoutParams para = binding.addRecommendImg.getLayoutParams();
            if (para.width!=-1){
                if (Tools.hasExternalStoragePermission(this)){
                    ImagePicker.with(this).cropSquare().compress(1024).maxResultSize(1080, 1080).createIntent(intent -> {
                        launcher.launch(intent);
                        return null;
                    });
                }else {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,Manifest.permission.MANAGE_EXTERNAL_STORAGE}, 0);
                }
            }else{
                AlertDialog.Builder dialog=new AlertDialog.Builder(this);
                dialog.setMessage(getResources().getString(R.string.deleteConfirm)).setPositiveButton(getResources().getString(R.string.delete), (dialogInterface, i) -> {
                    para.height=Tools.px2dip(this,originWidth);
                    para.width=Tools.px2dip(this,originWidth);
                    binding.addRecommendImg.setLayoutParams(para);
                    binding.addRecommendImg.setImageResource(R.drawable.add_post);
                    post_file.delete();
                }).setNegativeButton(getResources().getString(R.string.cancel),null).show();
            }
        });

        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == Activity.RESULT_OK) {
                post_file = new File(Objects.requireNonNull(result.getData()).getData().getPath());
                ViewGroup.LayoutParams para = binding.addRecommendImg.getLayoutParams();
                if (para.width==-1){
                    para.height=Tools.px2dip(this,originWidth);
                    para.width=Tools.px2dip(this,originWidth);
                }else {
                    para.height=-1;
                    para.width=-1;
                }
                binding.addRecommendImg.setLayoutParams(para);
                binding.addRecommendImg.setImageBitmap(BitmapFactory.decodeFile(post_file.getAbsolutePath()));
            } else if (result.getResultCode() == ImagePicker.RESULT_ERROR) {
                Tools.toast(ImagePicker.getError(result.getData()));
            }
        });

    }
}